/*
 * Copyright (C) 2010-2011 Comcast Cable.  All Rights Reserved.
 */
package com.hercules.android.receiver.connection.parser.json.itemparsers;

import com.google.gjson.JSONException;
import com.google.gjson.JSONObject;
import com.hercules.android.receiver.connection.parser.CommandParsingException;
import com.hercules.android.receiver.connection.parser.MalformedCommandException;

import java.util.HashMap;
import java.util.Map;

/**
 * Parser for Map properties.
 * <p>
 * AndroidAssembly2 this class was added in Android Assembly 2
 *
 * @author 7realm
 * @version 1.0
 */
public class MapParser extends DependentParser {
    /**
     * Constructor for {@link MapParser}.
     *
     * @param required if property is required
     * @param dependent the name of dependent property
     */
    public MapParser(boolean required, String dependent) {
        super(required, dependent);
    }

    /**
     * Parses map property.
     *
     * @param path the path to value
     * @param json the JSON
     * @param keyName the name of current JSON key
     * @param instance the instance of object, parsed value will be set to it
     * @return the parsed value
     * @throws CommandParsingException if error occurs while parsing
     */
    @Override
    protected Object doParse(StringBuilder path, JSONObject json, String keyName, Object instance)
        throws CommandParsingException {
        super.doParse(path, json, keyName, instance);

        try {
        	JSONObject value = json.get(keyName).isObject();
            // AndroidAssembly3 handle null case
            if (value == null || value.isNull() != null) {
                return null;
            }

            Map<String, Object> result = new HashMap<String, Object>();

            // parse map
            parseMap(path, value, result, SetterType.MAP);

            return result;
        } catch (JSONException e) {
            throw new MalformedCommandException("Expected JSON object at '" + keyName + "' at JSON '" + json + "'.", e);
        }
    }
}
